package com.powernode.Strategy.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.powernode.Strategy.LoginStrategy;
import com.powernode.constant.AuthConstants;
import com.powernode.domain.LoginSysUser;
import com.powernode.mapper.LoginSysUserMapper;
import com.powernode.model.SecurityUser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Set;

/**
 * 具体测策略类 , 实现抽象策略类接口定义的算法
 */
@Service(AuthConstants.SYS_USER_LOGIN)
public class SysUserLoginStrategyImpl implements LoginStrategy {

    @Resource
    private LoginSysUserMapper loginSysUserMapper;

    /**
     * 真正处理登录的方法 -- 后台管理系统用户的登录逻辑
     * 获取 用户信息
     * 判断 用户是否存在
     * 存在
     * 查询该用户权限
     * 判断是否包含该权限
     *
     * @param username
     * @return
     */
    @Override
    public UserDetails realLogin(String username) {
        LoginSysUser loginSysUser = loginSysUserMapper.selectOne(new LambdaQueryWrapper<LoginSysUser>().eq(LoginSysUser::getUsername, username));
        if (!ObjectUtils.isEmpty(loginSysUser)) {
            // 存在 -- 查询用户权限并判断权限
            Set<String> perms = loginSysUserMapper.selectPermsBySysUserId(loginSysUser.getUserId());
            // 将权限存入 到 权限用户对象中的 perms中 , 但是应将数据格式化后再进行存入
            SecurityUser securityUser = new SecurityUser();
            securityUser.setUserId(loginSysUser.getUserId());
            securityUser.setUsername(loginSysUser.getUsername());
            securityUser.setPassword(loginSysUser.getPassword());
            securityUser.setLoginType(AuthConstants.SYS_USER_LOGIN);
            securityUser.setStatus(loginSysUser.getStatus());
            securityUser.setShopId(loginSysUser.getShopId());
            // 判断是否存在 权限
            if (!CollectionUtils.isEmpty(perms)) {
                // 不为空 , 将群贤格式化设置
                securityUser.setPerms(perms);
            }
            return securityUser;
        }
        return null;
    }
}
